package com.smarthome.api.mobile.service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import com.smarthome.base.service.ShOrdersPaymentService;
import com.smarthome.base.service.ShOrdersService;
import com.smarthome.common.mobile.Service;
import com.smarthome.core.payment.alipay.AlipayService;
import com.smarthome.domain.bean.ShOrders;
import com.smarthome.domain.bean.ShOrdersPayment;
import com.smarthome.domain.enums.AppIdEnum;
import com.smarthome.domain.enums.OrdersPaymentStatus;
import com.smarthome.domain.enums.PropertyFeePaymentStatusEnum;
import com.smarthome.domain.mobile.MobileCodeEnum;
import com.smarthome.domain.mobile.MobileResponse;
import com.smarthome.domain.mobile.req.MobileOrdersPaymentReuqest;

@org.springframework.stereotype.Service("mobile.orders.pay")
public class MobileOrdersPaymentService implements Service<MobileResponse<Map<String, String>>> {

    @Resource
    private ShOrdersService shOrdersService;
    @Resource
    private ShOrdersPaymentService shOrdersPaymentService;
    @Resource
    private AlipayService alipayService;

    /**
     * 生成缴费记录
     * @param request
     * @param response
     */
    public void applyPay(MobileOrdersPaymentReuqest request, MobileResponse<Map<String, String>> response) {
        ShOrders order = shOrdersService.selectEntryById(request.getOrderId());
        if (null == order) {
            response.setMobileCodeObj(MobileCodeEnum.ORDERS_NOT_EXISTS);
            return;
        }
        if (order.getPaymentStatus() != OrdersPaymentStatus.DEEPEND.getType()) {
            response.setMobileCodeObj(MobileCodeEnum.ORDERS_IS_PAID);
            return;
        }
        // 生成订单缴费记录
        ShOrdersPayment payment = new ShOrdersPayment();
        payment.setAccountId(request.getAccountId());
        payment.setChannelSn(request.getChannelSn());
        payment.setOrderId(request.getOrderId());
        payment.setAmount(order.getAmount());
        payment.setStatus(PropertyFeePaymentStatusEnum.DEPEND.getCode());
        long paymentSn = new Date().getTime();
        payment.setPaymentSn(AppIdEnum.ORDERS.getCode() + "_" + String.valueOf(paymentSn));
        shOrdersPaymentService.saveOrUpdate(payment);
        Map<String, String> res = new HashMap<String, String>();
        res.put("alipayStr", alipayService.payByAlipayMobile(AppIdEnum.ORDERS.getCode(), payment.getPaymentSn(), order.getAmount(), "订单支付"));
        response.setData(res);
    }

}
